package com.corticon.dialogs.designer.licence;


import javax.annotation.Resource;

import com.corticon.dialogs.dao.UserDAO;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.apache.commons.codec.binary.Base64.decodeBase64;

public class LicenceManager {
    //private static final Logger LOG = Logger.getLogger(LicenceManager.class);

    private String expiredDate;
    private String userCount;
    private String userName;

    // Public Key encoded with Base64
    private String publicKeyBase64;

    // Signature for properties string with Base64
    private String signatureBase64;

    // Properties string separated with common.
    // The order is expiredDate,userCount,userName
    private String properties;

    private String licenseBase64;
    private boolean valid = false;

    @Resource
    private UserDAO userDAO;
    
    public void load(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        String lineString = "";

        try {
            reader = new BufferedReader(new FileReader(file));
            if ((lineString = reader.readLine()) == null) {
                return;
            }
            reader.close();
        } catch (FileNotFoundException e) {
            valid = false;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                 reader.close();
                } catch (IOException e) {
                 e.printStackTrace();
                }
            }
        }
        licenseBase64 = lineString;
    }

    /**
     * Verify the signature
     * @return
     */
    public boolean verify() {
        if (licenseBase64 == null || "".equals(licenseBase64)) {
            return false;
        }
        if (!setItems())
            return false;
        try {
            valid = Coder.verify(properties.getBytes(), publicKeyBase64, signatureBase64);
        } catch (Exception e) {
            valid = false;
        }
        return valid;
    }
    public boolean checkExpiredDate() {
        if (!valid)
            return false;
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = myFormatter.parse(expiredDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date.after(new Date());
    }
    public boolean checkMAXUser() {
        if (!valid)
            return false;
        return userDAO.getCountAll() < Integer.parseInt(userCount);
    }
    public boolean isValid(){
        return valid;
    }

    /**
     * parse every item from license file
     */
    private boolean setItems() {
        // Get the license data decoded by Base64.
        String license = Coder.bytesToString(decodeBase64(licenseBase64.getBytes()));

        // Get every item separated by "|"
        String[] licenseArray = license.split("\\|");
        try {
            signatureBase64 = licenseArray[0];
            publicKeyBase64 = licenseArray[1];
            properties = licenseArray[2];

            // Get every property separated by ","
            String[] dataArray = this.properties.split(",");
            expiredDate = dataArray[0];
            userCount = dataArray[1];
            userName = dataArray[2];
            return true;
        } catch (ArrayIndexOutOfBoundsException e) {
            return false;
        }
    }
}